<?php

/*
  +--------------------------------------------------------------------------
  |   Invision Power Board
  |   =============================================
  |   by Matthew Mecham
  |   (c) 2001 - 2006 Invision Power Services, Inc.
  |
  |   =============================================
  |
  |
  +---------------------------------------------------------------------------
  |   > $Date: 2007-03-07 16:47:18 -0500 (Wed, 07 Mar 2007) $
  |   > $Revision: 872 $
  |   > $Author: bfarber $
  +---------------------------------------------------------------------------
  |
  |   > Board index module
  |   > Module written by Matt Mecham
  |   > Date started: 17th February 2002
  |
  |	> Module Version Number: 1.0.0
  |   > DBA Checked: Wed 19 May 2004
  |   > Quality Checked: Wed 15 Sept. 2004
  +--------------------------------------------------------------------------
 */

if (!defined('IN_IPB')) {
    print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
    exit();
}

class boards {
    # Global

    var $ipsclass;
    var $output = "";
    var $base_url = "";
    var $html = "";
    var $forums = array();
    var $mods = array();
    var $cats = array();
    var $children = array();
    var $nav;
    var $db_row = array();
    var $news_topic_id = "";
    var $news_forum_id = "";
    var $news_title = "";
    var $sep_char = "";
    var $statfunc = "";

    /* ------------------------------------------------------------------------- */

    // INIT
    /* ------------------------------------------------------------------------- */

    function init() {
        $this->base_url = $this->ipsclass->base_url;

        // Get more words for this invocation!

        $this->ipsclass->load_language('lang_boards');

        $this->ipsclass->load_template('skin_boards');
    }

    /* ------------------------------------------------------------------------- */

    // Auto run function
    /* ------------------------------------------------------------------------- */

    function auto_run() {
        //-----------------------------------------
        // Get the emailer module
        //-----------------------------------------

        require ROOT_PATH . "sources/classes/class_email.php";

        $this->email = new emailer();
        $this->email->ipsclass = & $this->ipsclass;
        $this->email->email_init();
        if (USE_MODULES == 1) {
            require ROOT_PATH . "modules/ipb_member_sync.php";

            $this->modules = new ipb_member_sync();
            $this->modules->ipsclass = & $this->ipsclass;
        }
        switch ($this->ipsclass->input['CODE']) {
            case 'logout':
                $this->logout();
                break;
            case 'termsread':// Read Terms
                $this->show_terms_read("", 1);
                break;
            case 'shortregister':
                $this->short_register();
                break;
            default:
                break;
        }
        $this->init();
        $this->statfunc = $this->ipsclass->load_class(ROOT_PATH . 'sources/lib/func_boardstats.php', 'func_boardstats');

        $this->statfunc->register_class($this);
        require_once( ROOT_PATH . 'sources/action_public/Common.php' );
        $common = new Common();
        $common->ipsclass = & $this->ipsclass;
        $common->parseLastVisit();
        
        if ($this->ipsclass->vars['ipbli_usertype'] != 'username') {
            $this->ipsclass->lang['qli_name'] = $this->ipsclass->lang['email_address'];
        }
        $this->output .= $this->ipsclass->compiled_templates['skin_boards']->PageTop($this->ipsclass->get_date($this->ipsclass->input['last_visit'], 'LONG'));

        //-----------------------------------------
        // Get DB markers
        //-----------------------------------------
        $this->boards_get_db_tracker();

        //-----------------------------------------
        // What are we doing?, Get all categories by Tuanhnm, Mainly
        //-----------------------------------------
        $this->process_all_cats();       
        
        //echo ( $this->output);exit();
        //-----------------------------------------
        // Add in show online users
        //-----------------------------------------

        $stats_html = "";
        $stats_output = "";
        $stats_html .= $this->statfunc->active_users();

        //-----------------------------------------
        // Are we viewing the calendar?
        //-----------------------------------------        
        $stats_html .= $this->statfunc->show_calendar_events();

        //-----------------------------------------
        // Add in show stats, statistic from forum
        //-----------------------------------------
        $stats_html .= $this->statfunc->show_totals();
        //echo $stats_html;exit();
        //var_dump($stats_html);
        //exit();

        if ($stats_html != "") {
            $collapsed_ids = ',' . $this->ipsclass->my_getcookie('collapseprefs') . ',';

            $show['div_fo'] = '';
            $show['div_fc'] = 'none';

            if (strstr($collapsed_ids, ',stat,')) {
                $show['div_fo'] = 'none';
                $show['div_fc'] = '';
            }

            // Begin render statistic html
//            $this->output .= $this->ipsclass->compiled_templates['skin_boards']->stats_header($this->statfunc->users_online, $this->statfunc->total_posts, $this->statfunc->total_members, $show);
//            $this->output .= $stats_html;
//            $this->output .= $this->ipsclass->compiled_templates['skin_boards']->stats_footer();
            $stats_output .= $this->ipsclass->compiled_templates['skin_boards']->stats_header($this->statfunc->users_online, $this->statfunc->total_posts, $this->statfunc->total_members, $show);
            $stats_output .= $stats_html;
            $stats_output .= $this->ipsclass->compiled_templates['skin_boards']->stats_footer();
            // End render statistic html
            
        }



        //-----------------------------------------
        // Add in board info footer
        //-----------------------------------------
        $this->output .= $this->ipsclass->compiled_templates['skin_boards']->bottom_links();

        //-----------------------------------------
        // Check for news forum.
        //-----------------------------------------
        if (isset($this->ipsclass->forums->forum_by_id[$this->ipsclass->vars['news_forum_id']]['newest_id']) AND $this->ipsclass->forums->forum_by_id[$this->ipsclass->vars['news_forum_id']]['newest_id'] AND $this->ipsclass->vars['index_news_link']) {
            $t_html = $this->ipsclass->compiled_templates['skin_boards']->newslink($this->news_forum_id, stripslashes($this->ipsclass->forums->forum_by_id[$this->ipsclass->vars['news_forum_id']]['newest_title']), $this->ipsclass->forums->forum_by_id[$this->ipsclass->vars['news_forum_id']]['newest_id']);

            $this->output = str_replace("<!-- IBF.NEWSLINK -->", "$t_html", $this->output);
        }
        
        //-----------------------------------------
        // Showing who's chatting NEW?
        // IPB3.0: To Do: move into components
        //-----------------------------------------

        $this->ipsclass->vars['chat04_account_no'] = $this->ipsclass->vars['chat04_account_no'] ? $this->ipsclass->vars['chat04_account_no'] : $this->ipsclass->vars['chat_account_no'];
        $this->ipsclass->vars['chat04_who_on'] = $this->ipsclass->vars['chat04_who_on'] ? $this->ipsclass->vars['chat04_who_on'] : $this->ipsclass->vars['chat_who_on'];

        if ($this->ipsclass->vars['chat04_account_no'] and $this->ipsclass->vars['chat04_who_on']) {
            require_once( ROOT_PATH . 'sources/lib/func_chat.php' );

            $chat = new func_chat();
            $chat->ipsclass = & $this->ipsclass;

            $chat->register_class($this);

            $chat_html = $chat->get_online_list();

            $this->output = str_replace("<!--IBF.WHOSCHATTING-->", $chat_html, $this->output);
        }
        //-----------------------------------------
        // Print as normal
        //-----------------------------------------       
        $this->ipsclass->print->add_output($this->output);

        $cp = "";

        if ($this->ipsclass->vars['ips_cp_purchase']) {
            $cp = "";
        }
        
        require_once( ROOT_PATH . 'sources/action_public/Common.php' );
        $common = new Common();
        $files = $common->read_dir($this->ipsclass->vars['flash_diectory_path']."social/");       
        $random_file = $files[array_rand($files)];
        $random_file2 = $files[array_rand($files)];
        do{
            $random_file2 = $files[array_rand($files)];
        }while ($random_file == $random_file2);

        //<% RANDOM_FLASH_PATH %><% RANDOM_FLASH %>
        $random_flash_path = "/flash/forum/";
        $this->output = str_replace("<% RANDOM_FLASH_PATH %>", $random_flash_path, $this->output);
        $this->output = str_replace("<% RANDOM_FLASH %>", $random_file, $this->output);
        $this->output = str_replace("<% RANDOM_FLASH2 %>", $random_file2, $this->output);
        $this->ipsclass->print->do_output(array('TITLE' => $this->ipsclass->vars['board_name'] . $cp, 'JS' => 0, 'NAV' => $this->nav, 'STATS_HTML' => $stats_output));
        
    }

    /* ------------------------------------------------------------------------- */

    //
    // Display sub forums
    //
    /* ------------------------------------------------------------------------- */
    function logout() {

        /*
         * delete cookie
         */
        //-----------------------------------------
        // Set some cookies
        //-----------------------------------------

        $this->ipsclass->my_setcookie("member_id", "0");
        $this->ipsclass->my_setcookie("pass_hash", "0");
        $this->ipsclass->my_setcookie("anonlogin", "-1");

        if (is_array($_COOKIE)) {
            $this->ipsclass->vars['cookie_id'] = preg_quote($this->ipsclass->vars['cookie_id']);

            foreach ($_COOKIE as $cookie => $value) {
                if (preg_match("/^(" . $this->ipsclass->vars['cookie_id'] . "ipbforumpass_.*$)/i", $cookie, $match)) {
                    $this->ipsclass->my_setcookie(str_replace($this->ipsclass->vars['cookie_id'], "", $match[0]), '-', -1);
                }
            }
        }
        //-----------------------------------------
        // Remote log out?
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();

        $this->ipsclass->DB->simple_construct(array('update' => 'sessions',
            'set' => "member_name='',member_id='0',login_type='0',member_group={$this->ipsclass->vars['guest_group']}",
            'where' => "id='" . $this->ipsclass->sess->session_id . "'"
        ));

        $this->ipsclass->DB->simple_shutdown_exec();
        list( $privacy, $loggedin ) = explode('&', $this->ipsclass->member['login_anonymous']);

        $this->ipsclass->DB->simple_construct(array('update' => 'members',
            'set' => "login_anonymous='{$privacy}&0', last_visit=" . time() . ", last_activity=" . time(),
            'where' => "id=" . intval($this->ipsclass->member['id'])
                )
        );

        $this->ipsclass->DB->simple_shutdown_exec();
        $this->ipsclass->boink_it($this->ipsclass->vars['board_url']);
    }

    function show_subforums($fid) {
        $this->init();
        //echo $fid;exit();
        $temp_html = "";
        $sub_output = "";

        //-----------------------------------------
        // Get show / hide cookah
        //-----------------------------------------

        $collapsed_ids = ',' . $this->ipsclass->my_getcookie('collapseprefs') . ',';
        
//        echo (isset($this->ipsclass->forums->forum_cache[$fid]) AND is_array($this->ipsclass->forums->forum_cache[$fid])) ? 'true':'false';exit();
        if (isset($this->ipsclass->forums->forum_cache[$fid]) AND is_array($this->ipsclass->forums->forum_cache[$fid])) {
            $cat_data = $this->ipsclass->forums->forum_by_id[$fid];
            //var_dump($cat_data);exit();
            $cat_data['div_fo'] = '';
            $cat_data['div_fc'] = 'none';

            if (strstr($collapsed_ids, ',' . $fid . ',') and ( $cat_data['sub_can_post'] == 1 )) {
                $cat_data['div_fo'] = 'none';
                $cat_data['div_fc'] = '';
            }

            // Require text code class for topic clean url
            require_once(KERNEL_PATH . "class_textcode.php");
            $this->ipsclass->textcode = new class_textcode();

            $count = 1;
            //var_dump($this->ipsclass->forums->forum_cache[$fid]);exit();
            foreach ($this->ipsclass->forums->forum_cache[$fid] as $forum_data) {
                $count++;
                $forum_data['css_row'] = $count % 2 + 1;
                $forum_data['_queued_img'] = isset($forum_data['_queued_img']) ? $forum_data['_queued_img'] : '';
                $forum_data['_queued_info'] = isset($forum_data['_queued_info']) ? $forum_data['_queued_info'] : '';
                $forum_data['show_subforums'] = isset($forum_data['show_subforums']) ? $forum_data['show_subforums'] : '';
                $forum_data['last_unread'] = isset($forum_data['last_unread']) ? $forum_data['last_unread'] : '';
                
                //-----------------------------------------
                // Get all subforum stats
                // and calculate
                //-----------------------------------------

                if (isset($this->ipsclass->vars['forum_cache_minimum']) AND $this->ipsclass->vars['forum_cache_minimum']) {
                    $forum_data['description'] = "<!--DESCRIPTION:{$forum_data['id']}-->";
                    $need_desc[] = $forum_data['id'];
                }

                if ($forum_data['redirect_on']) {
                    $forum_data['redirect_hits'] = $this->ipsclass->do_number_format($forum_data['redirect_hits']);

                    $forum_data['redirect_target'] = isset($forum_data['redirect_target']) ? $forum_data['redirect_target'] : '_parent';

                    $temp_html .= $this->ipsclass->compiled_templates['skin_boards']->forum_redirect_row($forum_data);
                } else {
                    $temp_html .= $this->ipsclass->compiled_templates['skin_boards']->ForumRow($this->ipsclass->forums->forums_format_lastinfo($this->ipsclass->forums->forums_calc_children($forum_data['id'], $forum_data)));
                }
            }
            
        }
        //echo $temp_html;exit();

        if ($temp_html) {
            $sub_output .= $this->ipsclass->compiled_templates['skin_boards']->subheader($cat_data);
            $sub_output .= $temp_html;
            $sub_output .= $this->ipsclass->compiled_templates['skin_boards']->end_this_cat();
        } else {
            return $sub_output;
        }

        unset($temp_html);

        $sub_output .= $this->ipsclass->compiled_templates['skin_boards']->end_all_cats();

        //-----------------------------------------
        // Get descriptions?
        //-----------------------------------------

        if (isset($this->ipsclass->vars['forum_cache_minimum']) AND $this->ipsclass->vars['forum_cache_minimum'] AND count($need_desc)) {
            $this->ipsclass->DB->simple_construct(array('select' => 'id,description', 'from' => 'forums', 'where' => 'id IN(' . implode(',', $need_desc) . ')'));
            $this->ipsclass->DB->simple_exec();

            while ($r = $this->ipsclass->DB->fetch_row()) {

                $sub_output = str_replace("<!--DESCRIPTION:{$r['id']}-->", $r['description'], $sub_output);
            }
        }


        return $sub_output;
    }

    /* ------------------------------------------------------------------------- */

    //
    // PROCESS ALL CATEGORIES
    //
    /* ------------------------------------------------------------------------- */

    function process_all_cats() {
        $need_desc = array();
        $root = array();
        $parent = array();
        //-----------------------------------------
        // Want to view categories?
        //-----------------------------------------
        if (isset($this->ipsclass->input['c']) AND $this->ipsclass->input['c']) {
            foreach (explode(",", $this->ipsclass->input['c']) as $c) {
                $c = intval($c);
                $i = $this->ipsclass->forums->forum_by_id[$c]['parent_id'];
                $root[$i] = $i;
                $parent[$c] = $c;
            }
        }
        
        if (!count($root)) {
            $root[] = 'root';
        }

        //-----------------------------------------
        // Get show / hide cookah
        //-----------------------------------------

        $collapsed_ids = ',' . $this->ipsclass->my_getcookie('collapseprefs') . ',';

        $this->ipsclass->forums->register_class($this);

        // Require text code class for topic clean url
        require_once(KERNEL_PATH . "class_textcode.php");
        $this->ipsclass->textcode = new class_textcode();
        
        // Each cache from forum by tuanhnm 
        foreach ($root as $root_id) {
            // Each sub-forum in cache by tuanhnm
            if (is_array($this->ipsclass->forums->forum_cache[$root_id]) and count($this->ipsclass->forums->forum_cache[$root_id])) {

                // Each category in sub-forum by tuanhnm
                foreach ($this->ipsclass->forums->forum_cache[$root_id] as $id => $forum_data) {
                    $temp_html = "";

                    //-----------------------------------------
                    // Only showing certain root forums?
                    //-----------------------------------------

                    if (count($parent)) {
                        if (!in_array($id, $parent)) {
                            continue;
                        }
                    }

                    $cat_data = $forum_data;

                    $cat_data['div_fo'] = '';
                    $cat_data['div_fc'] = 'none';

                    if (strstr($collapsed_ids, ',' . $cat_data['id'] . ',')) {
                        $cat_data['div_fo'] = 'none';
                        $cat_data['div_fc'] = '';
                    }
                    //var_dump($this->ipsclass->forums->forum_cache[$forum_data['id']]);exit();
                    if (isset($this->ipsclass->forums->forum_cache[$forum_data['id']]) AND is_array($this->ipsclass->forums->forum_cache[$forum_data['id']])) {
                        // Added by BabyWolf
                        $count = 0;

                        foreach ($this->ipsclass->forums->forum_cache[$forum_data['id']] as $forum_data) {
                            $forum_data['show_subforums'] = isset($forum_data['show_subforums']) ? $forum_data['show_subforums'] : '';
                            $forum_data['_queued_img'] = isset($forum_data['_queued_img']) ? $forum_data['_queued_img'] : '';
                            $forum_data['_queued_info'] = isset($forum_data['_queued_info']) ? $forum_data['_queued_info'] : '';
                            $forum_data['last_unread'] = isset($forum_data['last_unread']) ? $forum_data['last_unread'] : '';
                            //var_dump($forum_data['last_topic']);
                            // Added by BabyWolf
                            $forum_data['css_row'] = $count % 2 + 1;
                            $count++;

                            //-----------------------------------------
                            // Get all subforum stats
                            // and calculate
                            //-----------------------------------------

                            if (isset($this->ipsclass->vars['forum_cache_minimum']) AND $this->ipsclass->vars['forum_cache_minimum']) {
                                $forum_data['description'] = "<!--DESCRIPTION:{$forum_data['id']}-->";
                                $need_desc[] = $forum_data['id'];
                            }
                            
                            if ($forum_data['redirect_on']) {
                                $forum_data['redirect_target'] = isset($forum_data['redirect_target']) ? $forum_data['redirect_target'] : '_parent';

                                $temp_html .= $this->ipsclass->compiled_templates['skin_boards']->forum_redirect_row($forum_data);
                            } else {
                                //var_dump($this->ipsclass->forums->forums_format_lastinfo($this->ipsclass->forums->forums_calc_children($forum_data['id'], $forum_data)));exit();
                                $temp_html .= $this->ipsclass->compiled_templates['skin_boards']->ForumRow($this->ipsclass->forums->forums_format_lastinfo($this->ipsclass->forums->forums_calc_children($forum_data['id'], $forum_data)));
                            }
                        }
                    }
                    //var_dump($cat_data);
                    // Render column block sub forum
                    if ($temp_html) {
                        $this->output .= $this->ipsclass->compiled_templates['skin_boards']->CatHeader_Expanded($cat_data);
                        $this->output .= $temp_html;
                        $this->output .= $this->ipsclass->compiled_templates['skin_boards']->end_this_cat();
                    }

                    unset($temp_html);
                }
            }
        }
        $this->output .= $this->ipsclass->compiled_templates['skin_boards']->end_all_cats();
        //-----------------------------------------
        // Get descriptions?
        //-----------------------------------------
        if (isset($this->ipsclass->vars['forum_cache_minimum']) AND $this->ipsclass->vars['forum_cache_minimum'] AND count($need_desc)) {
            $this->ipsclass->DB->simple_construct(array('select' => 'id,description', 'from' => 'forums', 'where' => 'id IN(' . implode(',', $need_desc) . ')'));
            $this->ipsclass->DB->simple_exec();

            while ($r = $this->ipsclass->DB->fetch_row()) {
                $this->output = str_replace("<!--DESCRIPTION:{$r['id']}-->", $r['description'], $this->output);
            }
        }
    }

    /* ------------------------------------------------------------------------- */

    // DB Tracker
    /* ------------------------------------------------------------------------- */

    function boards_get_db_tracker() {
        if ($this->ipsclass->vars['db_topic_read_cutoff'] and $this->ipsclass->member['id']) {
            $this->ipsclass->DB->simple_construct(array('select' => '*',
                'from' => 'topic_markers',
                'where' => "marker_member_id=" . $this->ipsclass->member['id'],
            ));

            $this->ipsclass->DB->simple_exec();

            while ($r = $this->ipsclass->DB->fetch_row()) {
                $this->ipsclass->forums->forum_by_id[$r['marker_forum_id']] =
                        isset($this->ipsclass->forums->forum_by_id[$r['marker_forum_id']]) ?
                        $this->ipsclass->forums->forum_by_id[$r['marker_forum_id']] :
                        array('parent_id' => 0);

                $this->ipsclass->forums->forum_cache[$this->ipsclass->forums->forum_by_id[$r['marker_forum_id']]['parent_id']][$r['marker_forum_id']]['_db_row'] = $r;
                $this->ipsclass->forums->forum_by_id[$r['marker_forum_id']]['_db_row'] = $r;
            }
        }
    }

    //-------------------------------------------
    // Begin show_terms_read
    //-------------------------------------------
    function show_terms_read($reg_code_err_msg="", $short_register=0) {
        
        //-----------------------------------------
        // INIT
        //-----------------------------------------
        if ($reg_code_err_msg) {
            $this->ipsclass->input = array_merge($this->ipsclass->input, $_SESSION);
            $_POST['act'] = 'termsread';
            $_POST = array_merge($_POST, $_SESSION);
        }

        if ($this->ipsclass->vars['ipbli_usertype'] == 'email') {
            $this->ipsclass->input['UserName'] = $this->ipsclass->input['members_display_name'];
        }

        $form_errors = array();
        $coppa = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
        $in_username = str_replace('|', '&#124;', $this->ipsclass->input['UserName']);
        $in_password = trim($this->ipsclass->input['PassWord']);
        $in_email = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $banfilters = array();
        $members_display_name = trim($this->ipsclass->input['members_display_name']);
        

        //-----------------------------------------
        // Load ban filters
        //-----------------------------------------

        $this->ipsclass->DB->simple_construct(array('select' => '*', 'from' => 'banfilters'));
        $this->ipsclass->DB->simple_exec();

        while ($r = $this->ipsclass->DB->fetch_row()) {
            $banfilters[$r['ban_type']][] = $r['ban_content'];
        }


        //-----------------------------------------
        // Custom profile field stuff
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/classes/class_custom_fields.php' );
        $fields = new custom_fields($this->ipsclass->DB);

        $fields->cache_data = $this->ipsclass->cache['profilefields'];

        $fields->init_data();
        $fields->parse_to_save(1);


        //-----------------------------------------
        // Remove multiple spaces in the username
        //-----------------------------------------

        $in_username = preg_replace("/\s{2,}/", " ", $in_username);
        //echo $in_username;exit();
        //-----------------------------------------
        // Remove linebreaks if set to
        //-----------------------------------------

        if ($this->ipsclass->vars['usernames_nobr']) {
            $in_username = $this->ipsclass->my_br2nl($in_username);
            $in_username = str_replace("\n", "", $in_username);
            $in_username = str_replace("\r", "", $in_username);

            $members_display_name = $this->ipsclass->my_br2nl($members_display_name);
            $members_display_name = str_replace("\n", "", $members_display_name);
            $members_display_name = str_replace("\r", "", $members_display_name);
        }

        //-----------------------------------------
        // Remove 'sneaky' spaces
        //-----------------------------------------

        if ($this->ipsclass->vars['strip_space_chr']) {
            // use hexdec to convert between '0xAD' and chr
            $in_username = str_replace(chr(160), ' ', $in_username);
            $in_username = str_replace(chr(173), ' ', $in_username);
            $in_username = str_replace(chr(240), ' ', $in_username);
            $members_display_name = str_replace(chr(160), ' ', $members_display_name);
            $members_display_name = str_replace(chr(173), ' ', $members_display_name);
            $members_display_name = str_replace(chr(240), ' ', $members_display_name);
        }

        //-----------------------------------------
        // Trim up..
        //-----------------------------------------

        $in_username = trim($in_username);

        //-----------------------------------------
        // Test unicode name too
        //-----------------------------------------

        $unicode_name = preg_replace_callback('/&#([0-9]+);/si', create_function('$matches', 'return chr($matches[1]);'), $in_username);
        $unicode_name = str_replace("'", '&#39;', $unicode_name);
        $unicode_name = str_replace("\\", '&#92;', $unicode_name);

        $unicode_dname = preg_replace_callback('/&#([0-9]+);/si', create_function('$matches', 'return chr($matches[1]);'), $members_display_name);
        $unicode_dname = str_replace("'", '&#39;', $unicode_dname);
        $unicode_dname = str_replace("\\", '&#92;', $unicode_dname);

        //-----------------------------------------
        // Check the email address
        //-----------------------------------------

        $in_email = $this->ipsclass->clean_email($in_email);

        if (!$in_email OR strlen($in_email) < 6) {
            echo "err_invalid_email";
            exit();
        }

        //-----------------------------------------
        // Test email address
        //-----------------------------------------
        // ---------------------------------------
        // Updated by hnmtuan on 06/08/2011
        // ---------------------------------------
        $this->ipsclass->input['EmailAddress'] = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $this->ipsclass->input['EmailAddress_two'] = $this->ipsclass->input['EmailAddress'];
        //$this->ipsclass->input['EmailAddress_two'] = strtolower( trim($this->ipsclass->input['EmailAddress_two']) );
        //$this->ipsclass->input['EmailAddress']     = strtolower( trim($this->ipsclass->input['EmailAddress']) );

        if (preg_match("#[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s]#", $this->ipsclass->input['EmailAddress_two'])) {
            echo "reg_error_email_invalid";
            exit();
        }

        //-----------------------------------------
        // More unicode..
        //-----------------------------------------

        $len_u = preg_replace("/&#([0-9]+);/", "-", $in_username);
        $len_p = preg_replace("/&#([0-9]+);/", "-", $in_password);
        $len_d = preg_replace("/&#([0-9]+);/", "-", $members_display_name);

        //-----------------------------------------
        // Test dname
        //-----------------------------------------

        if ($this->ipsclass->vars['auth_allow_dnames']) {
            if (!$members_display_name OR strlen($len_d) < 3 OR strlen($len_d) > $this->ipsclass->vars['max_user_name_length']) {
                echo "reg_error_no_name";
                exit();
            }
        }

        $this->ipsclass->vars['username_characters'] = 0;
        if ($this->ipsclass->vars['username_characters']) {
            $check_against = preg_quote($this->ipsclass->vars['username_characters'], "/");

            if (!preg_match("/^[" . $check_against . "]+$/i", $_POST['UserName']) && $this->ipsclass->vars['ipbli_usertype'] == 'username') {
                echo "username_characters";
                exit();
            }

            if (!preg_match("/^[" . $check_against . "]+$/i", $_POST['members_display_name']) && $this->ipsclass->vars['auth_allow_dnames']) {
                echo "username_characters";
                exit();
            }
        }

        //-----------------------------------------
        // Check for errors in the input.
        //-----------------------------------------

        if (!$in_username OR strlen($len_u) < 4 OR strlen($len_u) > $this->ipsclass->vars['max_user_name_length']) {
            //$form_errors['username'][$this->ipsclass->lang['reg_error_username_none']] = $this->ipsclass->lang['reg_error_username_none'];
            echo "reg_error_username_none";
            exit();
        }

        if (!$in_password OR strlen($len_p) < 6 OR strlen($len_p) > $this->ipsclass->vars['max_user_name_length']) {
            //$form_errors['password'][$this->ipsclass->lang['reg_error_no_pass']] = $this->ipsclass->lang['reg_error_no_pass'];
            echo "reg_error_no_pass";
            exit();
        }


        //-----------------------------------------
        // CHECK 1: Any errors (missing fields, etc)?
        //-----------------------------------------				
//        if (count($form_errors)) {
//            $this->show_page($form_errors);
//            return;
//        }
        //-----------------------------------------
        // USERNAME: Is this name already taken?
        //-----------------------------------------

        $this->ipsclass->DB->cache_add_query('login_getmember', array('username' => strtolower($in_username)));
        $this->ipsclass->DB->cache_exec_query();

        if ($name_check['id']) {
            echo "reg_error_username_taken";
            exit();
        }

        //-----------------------------------------
        // USERNAME: Is this name already taken (display)?
        //-----------------------------------------

        if ($this->ipsclass->vars['auth_allow_dnames']) {
            if ($this->ipsclass->vars['auth_dnames_nologinname']) {
                $this->ipsclass->DB->build_query(array('select' => "members_display_name, id",
                    'from' => 'members',
                    'where' => "members_l_display_name='" . strtolower($in_username) . "'",
                    'limit' => array(0, 1)));

                $this->ipsclass->DB->exec_query();

                if ($this->ipsclass->DB->get_num_rows()) {
                    echo "d_reg_error_username_taken";
                    exit();
                }
            }
        }

        //-----------------------------------------
        // UNAME: Check for existing LOG IN name.
        //-----------------------------------------

        $this->ipsclass->DB->build_query(array('select' => "name, id",
            'from' => 'members',
            'where' => "name='" . strtolower($in_username) . "'",
            'limit' => array(0, 1)));
        $this->ipsclass->DB->exec_query();

        if ($this->ipsclass->DB->get_num_rows()) {
            echo "u_reg_error_taken";
            exit();
        }
        //-----------------------------------------
        // USERNAME: Special chars?
        //-----------------------------------------

        if ($unicode_name != $in_username) {
            $this->ipsclass->DB->cache_add_query('login_getmember', array('username' => $this->ipsclass->DB->add_slashes(strtolower($unicode_name))));
            $this->ipsclass->DB->cache_exec_query();

            $name_check = $this->ipsclass->DB->fetch_row();

            if ($name_check['id']) {
                echo "reg_error_username_taken";
                exit();
            }
        }

        //-----------------------------------------
        // USERNAME: GUEST
        //-----------------------------------------

        if (strtolower($in_username) == 'guest') {
            echo "reg_error_username_taken";
            exit();
        }

        //-----------------------------------------
        // USERNAME: Banned?
        //-----------------------------------------

        if (is_array($banfilters['name']) and count($banfilters['name'])) {
            foreach ($banfilters['name'] as $n) {
                $n = str_replace('\*', '.*', preg_quote($n, "/"));

                if ($n AND preg_match("/^{$n}$/i", $in_username)) {
                    echo "reg_error_username_taken";
                    exit();
                }
            }
        }

        //-----------------------------------------
        // DNAME
        //-----------------------------------------

        if ($this->ipsclass->vars['auth_allow_dnames']) {
            //-----------------------------------------
            // Illegal characters
            //-----------------------------------------

            if (preg_match("#[\[\];,\|]#", str_replace('&#39;', "'", str_replace('&amp;', '&', $unicode_dname)))) {
                echo "d_reg_error_chars";
                exit();
            }

            //-----------------------------------------
            // DNAME: Is this name already taken?
            //-----------------------------------------

            $this->ipsclass->DB->cache_add_query('general_get_by_display_name', array('members_display_name' => strtolower($members_display_name)));
            $this->ipsclass->DB->cache_exec_query();

            $name_check = $this->ipsclass->DB->fetch_row();

            if ($name_check['id']) {
                echo "d_reg_error_taken";
                exit();
            }

            //-----------------------------------------
            // DNAME: Check for existing LOG IN name.
            //-----------------------------------------

            if ($this->ipsclass->vars['auth_dnames_nologinname']) {
                $this->ipsclass->DB->build_query(array('select' => "members_display_name, id",
                    'from' => 'members',
                    'where' => "members_l_username='" . strtolower($members_display_name) . "'",
                    'limit' => array(0, 1)));

                $this->ipsclass->DB->exec_query();

                if ($this->ipsclass->DB->get_num_rows()) {
                    echo "d_reg_error_taken";
                    exit();
                }
            }

            //-----------------------------------------
            // DNAME: Special chars?
            //-----------------------------------------

            if ($unicode_dname != $members_display_name) {
                $this->ipsclass->DB->cache_add_query('general_get_by_display_name', array('members_display_name' => $this->ipsclass->DB->add_slashes(strtolower($unicode_dname))));
                $this->ipsclass->DB->cache_exec_query();

                $name_check = $this->ipsclass->DB->fetch_row();

                if ($name_check['id']) {
                    echo "d_reg_error_taken";
                    exit();
                }
            }

            //-----------------------------------------
            // DNAME: Banned?
            //-----------------------------------------
//            if (is_array($banfilters['name']) and count($banfilters['name'])) {
//                foreach ($banfilters['name'] as $n) {
//                    $n = str_replace('\*', '.*', preg_quote($n, "/"));
//
//                    if ($n AND preg_match("/^{$n}$/i", $members_display_name)) {
//                        echo "d_reg_error_taken";
//                        exit();
//                    }
//                }
//            }
            //-----------------------------------------
            // DNAME: GUEST
            //-----------------------------------------

            if (strtolower($members_display_name) == 'guest') {
                echo "d_reg_error_taken";
                exit();
            }
        }

        //-----------------------------------------
        // Is this email addy taken? CONVERGE THIS??
        //-----------------------------------------

        if ($this->ipsclass->converge->converge_check_for_member_by_email($in_email) == TRUE) {
            echo "reg_error_email_taken";
            exit();
        }
        //echo "reg_error_email_taken";exit();
        //-----------------------------------------
        // Load handler...
        //-----------------------------------------

        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
        $this->han_login = new han_login();
        $this->han_login->ipsclass = & $this->ipsclass;
        $this->han_login->init();
        $this->han_login->email_exists_check($email);

        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'EMAIL_NOT_IN_USE') {
            echo "reg_error_email_taken";
            exit();
        }

        //-----------------------------------------
        // Are they banned [EMAIL]?
        //-----------------------------------------

        if (is_array($banfilters['email']) and count($banfilters['email'])) {
            foreach ($banfilters['email'] as $email) {
                $email = str_replace('\*', '.*', preg_quote($email, "/"));

                if (preg_match("/^{$email}$/i", $in_email)) {
                    echo "reg_error_email_ban";
                    exit();
                }
            }
        }

        //-----------------------------------------
        // CHECK 2: Any errors (duplicate names, etc)?
        //-----------------------------------------
//        if (count($form_errors)) {
//            $this->show_page($form_errors);
//            return;
//        }
        //-----------------------------------------
        // INIT
        //-----------------------------------------
//        $final_errors = array();
//        if ($this->ipsclass->vars['no_reg'] == 1) {
//            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'reg_off'));
//        }

        $coppa = $this->ipsclass->my_getcookie('coppa');

//        if ($coppa == 'yes') {
//            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'awaiting_coppa'));
//        }
//        $this->ipsclass->vars['username_errormsg'] = str_replace('{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg']);
//        if ($this->ipsclass->member['id']) {
//            //-----------------------------------------
//            // Log member out
//            //-----------------------------------------
//
//            require_once( ROOT_PATH . 'sources/action_public/login.php' );
//            $login = new login();
//            $login->ipsclass = & $this->ipsclass;
//            $login->do_log_out(0);
//        }
        //var_dump($_SESSION);exit();
        //-----------------------------------------
        // Continue
        //-----------------------------------------
        if (is_array($var)) {
            $_SESSION = array_merge($_SESSION, array('coppa_user' => $this->ipsclass->input['coppa_user'],
                'UserName' => $this->ipsclass->input['UserName'],
                'members_display_name' => $this->ipsclass->input['members_display_name'],
                'day' => $this->ipsclass->input['day'],
                'month' => $this->ipsclass->input['month'],
                'year' => $this->ipsclass->input['year'],
                'EmailAddress' => $this->ipsclass->input['EmailAddress'],
                'EmailAddress_two' => $this->ipsclass->input['EmailAddress_two'],
                'PassWord' => $this->ipsclass->input['PassWord'],
                'PassWord_Check' => $this->ipsclass->input['PassWord_Check'],
                'country' => $this->ipsclass->input['country'],
                'city' => $this->ipsclass->input['city'],
                'district' => $this->ipsclass->input['district'],
                'ward' => $this->ipsclass->input['ward'],
                'address' => $this->ipsclass->input['address'],
                'siteLocation' => $this->ipsclass->input['siteLocation']
                    )
            );
        } else {
            $_SESSION = array('coppa_user' => $this->ipsclass->input['coppa_user'],
                'UserName' => $this->ipsclass->input['UserName'],
                'members_display_name' => $this->ipsclass->input['members_display_name'],
                'day' => $this->ipsclass->input['day'],
                'month' => $this->ipsclass->input['month'],
                'year' => $this->ipsclass->input['year'],
                'EmailAddress' => $this->ipsclass->input['EmailAddress'],
                'EmailAddress_two' => $this->ipsclass->input['EmailAddress_two'],
                'PassWord' => $this->ipsclass->input['PassWord'],
                'PassWord_Check' => $this->ipsclass->input['PassWord_Check'],
                'country' => $this->ipsclass->input['country'],
                'city' => $this->ipsclass->input['city'],
                'district' => $this->ipsclass->input['district'],
                'ward' => $this->ipsclass->input['ward'],
                'address' => $this->ipsclass->input['address'],
                'siteLocation' => $this->ipsclass->input['siteLocation']
            );
        }


        //-----------------------------------------
        // Is this email addy taken? CONVERGE THIS??
        //-----------------------------------------
//        if ($this->ipsclass->converge->converge_check_for_member_by_email($in_email) == TRUE) {
//            echo "reg_error_email_taken";
//            exit();
//        }
        //-----------------------------------------
        // Load handler...
        //-----------------------------------------
//        require_once( ROOT_PATH . 'sources/handlers/han_login.php' );
//        $this->han_login = new han_login();
//        $this->han_login->ipsclass = & $this->ipsclass;
//        $this->han_login->init();
//        $this->han_login->email_exists_check($email);
//
//        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'EMAIL_NOT_IN_USE') {
//            echo "reg_error_email_taken";
//            exit();
//        }
        //-----------------------------------------
        // Are they banned [EMAIL]?
        //-----------------------------------------
//        if (is_array($banfilters['email']) and count($banfilters['email'])) {
//            foreach ($banfilters['email'] as $email) {
//                $email = str_replace('\*', '.*', preg_quote($email, "/"));
//
//                if (preg_match("/^{$email}$/i", $in_email)) {
//                    echo "reg_error_email_ban";
//                    exit();
//                }
//            }
//        }
        //-----------------------------------------
        // INIT
        //-----------------------------------------
//        $final_errors = array();
//        if ($this->ipsclass->vars['no_reg'] == 1) {
//            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'reg_off'));
//        }
//        $coppa = $this->ipsclass->my_getcookie('coppa');
        //$coppa = (isset($this->ipsclass->input['coppa_user']) AND $this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
//        if ($coppa == 'yes') {
//            $this->ipsclass->Error(array('LEVEL' => 1, 'MSG' => 'awaiting_coppa'));
//            //echo "awaiting_coppa";
//            //exit();
//        }
//        $this->ipsclass->vars['username_errormsg'] = str_replace('{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg']);
        //require_once('recaptchalib.php');
        require_once( ROOT_PATH . 'sources/classes/recaptchalib.php' );
        $privatekey = $this->ipsclass->vars['go_recapcha_private_key'];
        $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);

        if ($resp->is_valid == false) {
            echo "capcha_key_invalid";
            //echo "dddd";
            exit();
        }
        if ($resp->error != "") {
            echo "capcha_key_invalid";
            //echo "eeee";
            exit();
        }
        if ($resp->error != null) {
            echo "capcha_key_invalid";
            //echo "fff";
            exit();
        }
//      if ($resp->is_valid != true || $resp->error == "" || $resp->error == null) {
//        // What happens when the CAPTCHA was entered incorrectly
//          echo "capcha_key_invalid";
//          exit();
//      }
//    if ($this->ipsclass->member['id']) {
//        //-----------------------------------------
//        // Log member out
//        //-----------------------------------------
//
//        require_once( ROOT_PATH . 'sources/action_public/login.php' );
//        $login = new login();
//        $login->ipsclass = & $this->ipsclass;
//        $login->do_log_out(0);
//    }
        //-----------------------------------------
        // Continue
        //-----------------------------------------
//    $_SESSION = array_merge($_SESSION, array('coppa_user' => $this->ipsclass->input['coppa_user'],
//        'UserName' => $this->ipsclass->input['UserName'],
//        'members_display_name' => $this->ipsclass->input['members_display_name'],
//        'day' => $this->ipsclass->input['day'],
//        'month' => $this->ipsclass->input['month'],
//        'year' => $this->ipsclass->input['year'],
//        'EmailAddress' => $this->ipsclass->input['EmailAddress'],
//        'EmailAddress_two' => $this->ipsclass->input['EmailAddress_two'],
//        'PassWord' => $this->ipsclass->input['PassWord'],
//        'PassWord_Check' => $this->ipsclass->input['PassWord_Check'],
//        'country' => $this->ipsclass->input['country'],
//        'city' => $this->ipsclass->input['city'],
//        'district' => $this->ipsclass->input['district'],
//        'ward' => $this->ipsclass->input['ward'],
//        'address' => $this->ipsclass->input['address'],
//        'siteLocation' => $this->ipsclass->input['siteLocation']
//            )
//    );
        // Set referer to redirect user back to their current page before they click on register link
        if (trim($this->ipsclass->input['referer']))
            $_SESSION['referer'] = $this->ipsclass->input['referer'];

        require_once( ROOT_PATH . 'sources/classes/class_custom_fields.php' );
        $fields = new custom_fields($this->ipsclass->DB);

        $fields->cache_data = $this->ipsclass->cache['profilefields'];
        //echo $this->ipsclass->cache['profilefields'];exit();
        $fields->init_data();
        $fields->parse_to_register();

        foreach ($fields->out_fields as $id => $data) {
            $_SESSION['field_' . $id] = $this->ipsclass->input['field_' . $id];
        }


        $cache = $this->ipsclass->DB->simple_exec_query(array('select' => '*', 'from' => 'conf_settings', 'where' => "conf_key='reg_rules'"));

        $text = $cache['conf_value'] ? $cache['conf_value'] : $cache['conf_default'];

        // Update by tuanhnm 
        // Check is short register state
        if ($short_register) {
            $result = $this->short_register();
            //echo $result + "dfdfdfdfdf";exit();
            if (trim($result) != "register_success") {
                //echo $result;
                exit();
            }
            //exit();
        }

        //$this->output .= $this->ipsclass->compiled_templates['skin_regportal']->show_terms($this->ipsclass->my_nl2br($text), $coppa);

        $this->page_title = $this->ipsclass->lang['page_title'];
        $this->nav = array($this->ipsclass->lang['page_title']);


        $this->page_title = $this->ipsclass->lang['page_title'];
        $this->nav = array($this->ipsclass->lang['page_title']);
        //echo $this->output;
        echo "register_success";
        exit();
    }

    //-------------------------------------------
    // Begin short_register
    //-------------------------------------------
    function short_register() {
        //-----------------------------------------
        // INIT
        //-----------------------------------------

        if ($this->ipsclass->vars['ipbli_usertype'] == 'email') {
            $this->ipsclass->input['UserName'] = $this->ipsclass->input['members_display_name'];
        }

        $form_errors = array();
        $coppa = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
        $in_username = str_replace('|', '&#124;', $this->ipsclass->input['UserName']);
        $in_password = trim($this->ipsclass->input['PassWord']);
        $in_email = strtolower(trim($this->ipsclass->input['EmailAddress']));
        $banfilters = array();
        $members_display_name = trim($this->ipsclass->input['members_display_name']);

        //-----------------------------------------
        // Build up the hashes
        //-----------------------------------------

        $mem_group = $this->ipsclass->vars['member_group'];

        //-----------------------------------------
        // Are we asking the member or admin to preview?
        //-----------------------------------------

        if ($this->ipsclass->vars['reg_auth_type']) {
            $mem_group = $this->ipsclass->vars['auth_group'];
        } else if ($coppa == 1) {
            $mem_group = $this->ipsclass->vars['auth_group'];
        } else if ($this->ipsclass->vars['subsm_enforce']) {
            $mem_group = $this->ipsclass->vars['subsm_nopkg_group'];
        }

        $_mke_time = ( $this->ipsclass->vars['login_key_expire'] ) ? ( time() + ( intval($this->ipsclass->vars['login_key_expire']) * 86400 ) ) : 0;

        $member = array(
            'name' => $in_username,
            'members_l_username' => strtolower($in_username),
            'members_display_name' => $this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username,
            'members_l_display_name' => strtolower($this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username ),
            'member_login_key' => $this->ipsclass->converge->generate_auto_log_in_key(),
            'member_login_key_expire' => $_mke_time,
            'email' => $in_email,
            'mgroup' => $mem_group,
            'posts' => 0,
            'joined' => time(),
            'ip_address' => $this->ipsclass->ip_address,
            'time_offset' => $this->ipsclass->input['time_offset'],
            'view_sigs' => 1,
            'email_pm' => 1,
            'view_img' => 1,
            'view_avs' => 1,
            'restrict_post' => 0,
            'view_pop' => 1,
            'msg_total' => 0,
            'new_msg' => 0,
            'coppa_user' => $coppa,
            'language' => $this->ipsclass->vars['default_language'],
            'members_auto_dst' => 1,
            'members_editor_choice' => $this->ipsclass->vars['ips_default_editor'],
            'allow_admin_mails' => intval($this->ipsclass->input['allow_admin_mail']),
            'hide_email' => $this->ipsclass->input['allow_member_mail'] ? 0 : 1,
            'subs_pkg_chosen' => intval($this->ipsclass->input['subspackage'])
        );

        //-----------------------------------------
        // Insert: CONVERGE
        //-----------------------------------------

        $salt = $this->ipsclass->converge->generate_password_salt(5);
        $passhash = $this->ipsclass->converge->generate_compiled_passhash($salt, md5($in_password));

        $converge = array('converge_email' => $in_email,
            'converge_joined' => time(),
            'converge_pass_hash' => $passhash,
            'converge_pass_salt' => str_replace('\\', "\\\\", $salt)
        );

        //-----------------------------------------
        // Add Converge: Member
        //-----------------------------------------
        $this->han_login->create_account(array('email' => $member['email'],
            'joined' => $member['joined'],
            'password' => $in_password,
            'ip_address' => $this->ipsclass->ip_address
        ));

        if ($this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'SUCCESS') {
            //$this->ipsclass->Error(array('LEVEL' => 5, 'MSG' => 'han_login_create_failed', 'EXTRA' => $this->han_login->return_details ? $this->han_login->return_details : $this->han_login->return_code));
            //return "han_login_create_failed";
            //exit();
        }

        $this->ipsclass->DB->do_insert('members_converge', $converge);

        //-----------------------------------------
        // Get converges auto_increment user_id
        //-----------------------------------------
        $member_id = $this->ipsclass->DB->get_insert_id();
        $member['id'] = $member_id;

        //-----------------------------------------
        // Insert: MEMBERS
        //-----------------------------------------
        $this->ipsclass->DB->force_data_type = array('name' => 'string', 'members_display_name' => 'string', 'members_l_username' => 'string', 'members_l_display_name' => 'string');

        $this->ipsclass->DB->do_insert('members', $member);

        //-----------------------------------------
        // Insert: MEMBER EXTRA
        //-----------------------------------------
        $this->ipsclass->DB->do_insert('member_extra', array('id' => $member_id,
            'vdirs' => 'in:Inbox|sent:Sent Items',
            'interests' => '',
            'signature' => '',
            'location' => $this->ipsclass->site_info['site_name']
        ));

        if ($_FILES['upload_avatar']['name'] != '' || $_FILES['upload_photo']['name'] != '') {
            require_once ROOT_PATH . "sources/lib/func_usercp.php";
            $this->lib = new func_usercp();
            $this->ipsclass->member = $member;
            $this->ipsclass->member['g_edit_profile'] = 1;
            $this->ipsclass->member['g_avatar_upload'] = 1;
            $this->lib->ipsclass = &$this->ipsclass;
        }

        if ($_FILES['upload_avatar']['name'] != '' || $_FILES['upload_photo']['name'] != '') {
            $this->ipsclass->member = $this->ipsclass->sess->authorise();
        }

        //-----------------------------------------
        // Insert into the custom profile fields DB
        //-----------------------------------------
        $this->ipsclass->DB->do_delete('pfields_content', 'member_id=' . $member['id']);

//        $this->ipsclass->DB->force_data_type = array();
//        foreach ($fields->out_fields as $_field => $_data) {
//            $this->ipsclass->DB->force_data_type[$_field] = 'string';
//        }

        $fields->out_fields['member_id'] = $member['id'];

        $this->ipsclass->DB->do_insert('pfields_content', $fields->out_fields);

        //-----------------------------------------
        // Use modules?
        //-----------------------------------------

        if (USE_MODULES == 1) {
            $this->modules->register_class($this);

            $member['password'] = trim($this->ipsclass->input['PassWord']);

            $this->modules->on_create_account($member);

            if ($this->modules->error == 1) {
                return;
            }

            $member['password'] = "";
        }

        //-----------------------------------------
        // Validation key
        //-----------------------------------------
        $validate_key = md5($this->ipsclass->make_password() . time());
        $time = time();

        if ($coppa != 1) {
            if (($this->ipsclass->vars['reg_auth_type'] == 'user' ) or
                    ($this->ipsclass->vars['reg_auth_type'] == 'admin') or
                    ($this->ipsclass->vars['reg_auth_type'] == 'admin_user')) {
                //-----------------------------------------
                // We want to validate all reg's via email,
                // after email verificiation has taken place,
                // we restore their previous group and remove the validate_key
                //-----------------------------------------

                $this->ipsclass->DB->do_insert('validating', array(
                    'vid' => $validate_key,
                    'member_id' => $member['id'],
                    'real_group' => $this->ipsclass->vars['subsm_enforce'] ? $this->ipsclass->vars['subsm_nopkg_group'] : $this->ipsclass->vars['member_group'],
                    'temp_group' => $this->ipsclass->vars['auth_group'],
                    'entry_date' => $time,
                    'coppa_user' => $coppa,
                    'new_reg' => 1,
                    'ip_address' => $member['ip_address']
                ));


                if ($this->ipsclass->vars['reg_auth_type'] == 'user' OR $this->ipsclass->vars['reg_auth_type'] == 'admin_user') {
                    $this->email->get_template("reg_validate");

                    $this->email->build_message(array(
                        'THE_LINK' => $this->base_url_nosess . "?act=Reg&CODE=03&uid=" . urlencode($member_id) . "&aid=" . urlencode($validate_key),
                        'NAME' => $member['members_display_name'],
                        'MAN_LINK' => $this->base_url_nosess . "?act=Reg&CODE=05",
                        'EMAIL' => $member['email'],
                        'ID' => $member_id,
                        'CODE' => $validate_key,
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $member['email'];

                    $this->email->send_mail();

                    $this->output = $this->ipsclass->compiled_templates['skin_register']->show_authorise($member);
                } else if ($this->ipsclass->vars['reg_auth_type'] == 'admin') {
                    $this->output = $this->ipsclass->compiled_templates['skin_register']->show_preview($member);
                }

                if ($this->ipsclass->vars['new_reg_notify']) {

                    $date = $this->ipsclass->get_date(time(), 'LONG', 1);

                    $this->email->get_template("admin_newuser");

                    $this->email->build_message(array(
                        'DATE' => $date,
                        'MEMBER_NAME' => $member['members_display_name'],
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email1'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $this->ipsclass->vars['email_in'];
                    $this->email->send_mail();
                }

                $this->page_title = $this->ipsclass->lang['reg_success'];

                $this->nav = array($this->ipsclass->lang['nav_reg']);
            } else {
                //-----------------------------------------
                // We don't want to preview, or get them to validate via email.
                //-----------------------------------------

                $this->ipsclass->cache['stats']['last_mem_name'] = $member['members_display_name'];
                $this->ipsclass->cache['stats']['last_mem_id'] = $member['id'];
                // Added by BabyWolf
                $this->ipsclass->cache['stats']['last_mem_username'] = $member['name'];
                $this->ipsclass->cache['stats']['mem_count'] += 1;

                $this->ipsclass->update_cache(array('name' => 'stats', 'array' => 1, 'deletefirst' => 0));

                if ($this->ipsclass->vars['new_reg_notify']) {
                    $date = $this->ipsclass->get_date(time(), 'LONG', 1);

                    $this->email->get_template("admin_newuser");

                    $this->email->build_message(array(
                        'DATE' => $date,
                        'MEMBER_NAME' => $member['members_display_name'],
                            )
                    );

                    $this->email->subject = $this->ipsclass->lang['new_registration_email1'] . $this->ipsclass->vars['board_name'];
                    $this->email->to = $this->ipsclass->vars['email_in'];
                    $this->email->send_mail();
                }

                $this->ipsclass->no_print_header = 0;

                $this->ipsclass->my_setcookie("pass_hash", $member['member_login_key'], 1);
                $this->ipsclass->my_setcookie("member_id", $member['id'], 1);
                $this->ipsclass->my_setcookie('session_id', '0', -1);

                $this->ipsclass->stronghold_set_cookie($member['id'], $member['member_login_key']);
//                $this->ipsclass->boink_it($this->ipsclass->base_url);
//                exit();
//                $url = 'http://www.worldgames.vn/index.php?';
//                $act = 'regportal';
//                $code = 'wg';
//                echo "&errorStatus=0";
//                echo "&urlRegister=" . $url;
//                echo "&act=" . $act;
//                echo "&CODE=" . $code;
                //$this->ipsclass->boink_it($this->ipsclass->base_url . '&act=login&CODE=autologin&fromreg=1');
            }
        } else {
            // This is a COPPA user, so lets tell them they registered OK and redirect to the form.

            $this->ipsclass->DB->do_insert('validating', array(
                'vid' => $validate_key,
                'member_id' => $member['id'],
                'real_group' => $this->ipsclass->vars['member_group'],
                'temp_group' => $this->ipsclass->vars['auth_group'],
                'entry_date' => $time,
                'coppa_user' => $coppa,
                'new_reg' => 1,
                'ip_address' => $member['ip_address']
            ));

            //$url = $this->ipsclass->base_url;
//            $this->ipsclass->boink_it($this->ipsclass->base_url);
//            exit();
//            $act = 'regportal';
//            $code = 'wg';
//            echo "&errorStatus=0";
//            echo "&urlRegister=" . $url;
//            echo "&act=" . $act;
//            echo "&CODE=" . $code;
            //$this->ipsclass->print->redirect_screen($this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12');
        }
        return "register_success";
    }

}

?>